package org.demo.base.jdbc.util;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtils {

    private static ThreadLocal<Connection> conectionThreadLocal = new ThreadLocal<Connection>();

    private JDBCUtils() {

    }

    public static Connection getConnection() throws SQLException {
        Connection connection = conectionThreadLocal.get();
        if(connection==null){
            DriverManager.registerDriver(new Driver());
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/zhaofei","root","root");
            conectionThreadLocal.set(connection);
        }
        return connection;
    }

    public static void beginTransaction() throws SQLException {
        Connection connection = getConnection();
        connection.setAutoCommit(false);
    }

    public static void commitTransaction() throws SQLException {
        Connection connection = getConnection();
        connection.commit();
        connection.close();

    }

    public static void rollBackTransaction() throws SQLException {
        Connection connection = getConnection();
        connection.rollback();
        connection.close();
    }

    public static void releaseConnection() throws SQLException {
        Connection connection = getConnection();
        connection.close();
    }

    public static void TransactionIsolation(int level) throws SQLException {
        Connection connection = getConnection();
        connection.setTransactionIsolation(level);
    }
}
